#! /usr/bin/env python
#coding=utf-8
from uliweb import expose
from sqlalchemy import *
from uliweb.orm import *
from uliweb.utils.pyini import Ini
from sqlalchemy.sql import select
from sqlalchemy.sql import and_, or_, not_
import time, sys
sys.path.insert(0, '../apps')

import datetime
from datetime import date
from get_month_quarter import *

#db = get_connection('sqlite:///../database.db', debug=False)
#调用get_month_quarter.py中get_db_connection()获取数据库联接
db = get_db_connection()

#meta = MetaData(db)
#db.metadata.reflect()

def run():
    
    #从settings.ini获取任务类型编号
    settings = Ini('../apps/settings.ini')

    #assignment_type = dict(settings.PARA.ASSIGNMENT_TYPE)

    req = db.metadata.tables['tasks_develop']
                       
    #获取本月月初和月末时间
    month_first_day,month_last_day,month_view = get_month()

    #计算本月新增准开发需求任务数，算法：开始日期小于或等于本月末and大于等于本月1日
    #new = select([req.c.kfzx,req.c.type,func.count(req.c.ass_id)]).group_by(req.c.kfzx)
    #统计项目延迟情况数
    xmyc = select([req.c.kfzx,req.c.delay_classes,func.count(req.c.task_id)],and_(req.c.status == '2')).group_by(req.c.delay_classes,req.c.kfzx)

    req_model = get_model('version_month_report_bbycfx')

    #插入数据前，先删除本月已有数据，该语句可以保证该脚本每个月多次跑批
    #db.execute(req_model.delete().where(req_model.c.month_date == month_last_day)) 
    req_model.remove(req_model.c.month_date == month_last_day)
    #print data
    # 按照任务类型存储统计数据

    xmyc_rs = xmyc.execute()

    #定义字典型data
    data = {}

    task_stage = dict(settings.PARA.TASK_DELAY_CLASSES)

    req_kfzx_model = get_model('kfzx')
    sel_kfzx = select([req_kfzx_model.c.id])
           
    #说明：t，k是用来判断data[in_type][in_kfzx]字典是否已经被初始化
    t = '0'
    k = 0
    for row in xmyc_rs:   
            in_kfzx,in_delay_classes,count = row
            #20110112增加如果延迟原因分类为空，则跳过该条统计
            if not in_delay_classes:
                #print u'延迟原因分类为空：',u'开发中心',in_kfzx,u'记录数',count
                continue
            in_delay_classes = long(in_delay_classes)
            if k != in_kfzx:
                k = in_kfzx
                data[in_kfzx] = {}
                for stages in task_stage:  #动态初始化data[in_kfzx] = {}
                    #    print 'stages',stages
                        tx = stages
                    #    print 'tx',tx
                        tx = long(tx)
                        y = 'delay_num_%02d' % tx
                        data[in_kfzx][y] = 0             
    #            print k
            y = 'delay_num_%02d' % in_delay_classes
    #        print y
    #        print in_type,in_kfzx
            data[in_kfzx]['kfzx'] = in_kfzx
            data[in_kfzx][y] = count
            data[in_kfzx]['month_date'] = month_last_day
            data[in_kfzx]['month'] = month_view
    #        print data        
    #        data[in_type]['delay_classes'] = in_delay_classes    

    #将本月准开发需求汇总数据赋值给total_num

    for t,v in data.items():
    #    print 't',t,'v',v
        r = req_model(**v)
        r.save()

if __name__ == '__main__':
    try:
        db.begin()
        run()
        db.commit()
        log.info("finish")
    except Exception, e:
        db.rollback()
        log.exception(e)
        log.error('error')
        raise
